package se.bth.wpl.filesystem;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;



/*
 * directory1/altrofile.img
 * directory2/
 * file.txt ( "mamma" )
 * 
 */

public class CreateZip  implements ICreateZip{
	private ArrayList<ZC> fzp;
	public CreateZip(){
		fzp=new ArrayList<ZC>();
	}
	public void addFileToZip(String path,String fileName, String content){
		fzp.add(new ZC(path,fileName,content));
	}
	
	public void createZip(HttpServletResponse response) throws IOException  {

	    // ..... process request

	    // ..... then respond
	    response.setContentType("application/zip");
	    response.setStatus(HttpServletResponse.SC_OK);

	    // note : intentionally no content-length set, automatic chunked transfer if stream is larger than the internal buffer of the response
	    ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());

	    byte[] buffer = new byte[1024 * 32];
	    try {
	            // case1: already have input stream, typically ByteArrayInputStream from a byte[] full of previoiusly prepared csv data
	    	
	    		Iterator<ZC> fzpi=fzp.iterator();
	    		while(fzpi.hasNext()){
	    			ZC zc= fzpi.next();
		            InputStream in = new BufferedInputStream(zc.getInputStream());
		            try {
		           
		            	String fullpath= zc.getPath()+zc.getFileName();
		            	
		                zipOut.putNextEntry(new ZipEntry(fullpath));
	
		                int length = 0;
		                while((length = in.read(buffer)) > 0) {
		                    zipOut.write(buffer, 0, length);
		                }
	
		                zipOut.closeEntry();
		            } finally {
		                in.close();
		            }
	    		}
	           
	            // case 2: write directly to output stream, i.e. you have your raw data but need to create csv representation

//	            zipOut.putNextEntry(new ZipEntry("SecondName"));
//
//	            // example setup, key is to use the below outputstream 'zipOut' write methods
//	            MySerializer mySerializer = new MySerializer(); // i.e. csv-writer
//	            Object myData = getMyData(); // the data to be processed by the serializer in order to make a csv file
//
//	            mySerializer.setOutput(zipOut);
//
//	            // write whatever you have to the zipOut
//	            mySerializer.write(myData);

//	            zipOut.closeEntry();

	            // repeat for the next file.. or make for-loop

	        }finally
		{ 
	        zipOut.close();
	    }
	}
//	private InputStream getMyFirstInputStream() throws IOException{
//
//		
//		
//		
//		  // Get a file service
//		  FileService fileService = FileServiceFactory.getFileService();
//
//		  // Create a new Blob file with mime-type "text/plain"
//		  AppEngineFile file = fileService.createNewBlobFile("text/plain");
//
//		  // Open a channel to write to it
//		  boolean lock = false;
//		  FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
//
//		  // Different standard Java ways of writing to the channel
//		  // are possible. Here we use a PrintWriter:
//		  PrintWriter out = new PrintWriter(Channels.newWriter(writeChannel, "UTF8"));
//		  out.println("The woods are lovely dark and deep. PDGNG");
//		  out.println("But I have promises to keep.");
//		  
//		  // Close without finalizing and save the file path for writing later
//		  out.close();
//		  String path = file.getFullPath();
//
//		  // Write more to the file in a separate request:
//		  file = new AppEngineFile(path);
//
//		  // This time lock because we intend to finalize
//		  lock = true;
//		  writeChannel = fileService.openWriteChannel(file, lock);
//
//		  // This time we write to the channel using standard Java
//		  writeChannel.write(ByteBuffer.wrap
//		            ("And miles to go before I sleep.".getBytes()));
//
//		  // Now finalize
//		  writeChannel.closeFinally();
//
//		  // Later, read from the file using the file API
//		  lock = false; // Let other people read at the same time
//		  FileReadChannel readChannel = fileService.openReadChannel(file, false);
//
//		  // Again, different standard Java ways of reading from the channel.
//		  BufferedReader reader =
//		          new BufferedReader(Channels.newReader(readChannel, "UTF8"));  
//		       String line = reader.readLine();
//		  // line = "The woods are lovely dark and deep."
//
//		  readChannel.close();
//
//		  // Now read from the file using the Blobstore API
////		  BlobKey blobKey = fileService.getBlobKey(file);
////		  BlobstoreService blobStoreService = BlobstoreServiceFactory.getBlobstoreService();
////		  String segment = new String(blobStoreService.fetchData(blobKey, 30, 40));
//		  
//		return new ByteArrayInputStream(line.getBytes());
//		
//	
//	
//	}

//	private Object getMyData() {
//		// TODO Auto-generated method stub
//		return null;
//	}
	
}
